import React, {useEffect, useState} from 'react'
import axios from "axios";
import {Button, Table} from "antd";

export default function Audit() {

    const {roleId,region,username}=JSON.parse(localStorage.getItem("token"))
    const[newsList,setNewsList]=useState([])
    useEffect(()=>{
        const roleObj =  {
            "1":"superadmin",
            "2":"admin",
            "3":"editor"
        }
        axios.get(`/news?auditState=1&_expand=category`).then(res=>{
            setNewsList(roleObj[roleId]==="superadmin"?res.data:
                [...res.data.filter(item=>item.region===region&&roleObj[item.roleId]==="editor"),
                    ...res.data.filter(item=>item.author===username)
                ])
        })
    },[roleId,region,username])
    const handlePass = (item,auditState,publishState) => {
        axios.patch(`/news/${item.id}`,{
            auditState,
            publishState
        }).then(res=>{
            setNewsList(newsList.filter(data=>data.id!==item.id))
        })
    }
    const columns = [
        {
            title: '新闻标题',
            dataIndex: 'title',
            render(title,item) {
                return <a href={`/#/news-manage/preview/${item.id}`}>{title}</a>
            }
        },
        {
            title: '作者',
            dataIndex: 'author',
        },
        {
            title: '新闻分类',
            dataIndex: 'category',
            render(category) {
                return <div>{category.title}</div>
            },
        },
        {
            title:'操作',
            render(item){
                return <div>
                    <Button type="primary" onClick={()=>handlePass(item,2,1)}>通过</Button>
                    <Button danger onClick={()=>handlePass(item,3,0)}>驳回</Button>
                </div>
            }
        }
    ];
    return (
        <div>
            <Table dataSource={newsList} columns={columns} pagination={{pageSize:8}} rowKey={item=>item.id} />
        </div>
    )
}
